package com.katesoft.scale4j.rttp.jobs;

import com.katesoft.scale4j.log.Logger;
import com.katesoft.scale4j.log.LogFactory;
import org.junit.Test;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.scope.context.StepContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

import java.util.HashMap;
import java.util.Map;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/** @author kate2007 */
public class CounterPerJobTasklet implements Tasklet
{
    private static final Logger LOGGER = LogFactory.getLogger(CounterPerJobTasklet.class);
    private static final Map<String, Integer> counter = new HashMap<String, Integer>();

    @Override
    public RepeatStatus execute(StepContribution contribution,
                                ChunkContext chunkContext) throws Exception
    {
        if (!counter.containsKey(chunkContext.getStepContext().getJobName())) {
            counter.put(chunkContext.getStepContext().getJobName(), 0);
        }
        counter.put(chunkContext.getStepContext().getJobName(), counter.get(chunkContext.getStepContext().getJobName()) + 1);
        LOGGER.debug("executed %s, counter = %s", chunkContext.getStepContext().getJobName(), counter.get(chunkContext.getStepContext().getJobName()));
        return null;
    }

    public static int getJobExecutionTimes(String jobName)
    {
        Integer integer = counter.get(jobName);
        int result = integer == null ? 0 : integer;
        LOGGER.debug("job %s was executed %s", jobName, result);
        return result;
    }

    public static void reset()
    {
        counter.clear();
    }

    @Test
    public void works() throws Exception
    {
        CounterPerJobTasklet tasklet = new CounterPerJobTasklet();
        ChunkContext context = mock(ChunkContext.class);
        StepContext stepContext = mock(StepContext.class);
        when(stepContext.getJobName()).thenReturn("job123");
        when(context.getStepContext()).thenReturn(stepContext);
        tasklet.execute(null, context);
        tasklet.execute(null, context);
        assertThat(getJobExecutionTimes("job123"), is(2));
    }
}
